/****************************************************************************

	COPYRIGHT(C) MAXSI SOFTWARE, JONAS 'SORTIE' TERMANSEN 2008, 2009, 2010

    This file is part of Maxsi Feedback.

    Maxsi Feedback is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Maxsi Feedback is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with Maxsi Feedback.  If not, see <http://www.gnu.org/licenses/>.

	*/ #include "MaxsiFeedbackContributors.h" /*

	If you modify this file, please enter your name below and provide contact
	information in MaxsiFeedbackContributors.h. For more information please see
	MaxsiFeedbackContributors.h.
	
	Contributors to this file:

	- Jonas 'Sortie' Termansen
	- [your name here]


	MaxsiFeedback.exe
	An User-Friendly approach to providing developers with instant feedback!
	
	Main.cpp
	Basic WIN32 functions and stuff

****************************************************************************/

#include "MaxsiEngine.h"
#include <io.h>
#include <direct.h>
#include <iostream> 
#include <fcntl.h>
#include <SYS\Stat.h>
#include "Main.h" 
#include "UI.h"
#include "Data.h"

ME_WIN32ENTRYPOINT(MaxsiFeedback);

/****************************************************************************

    FUNCTION: WinMain(HANDLE, HANDLE, LPSTR, int)
    PURPOSE: calls initialization function, processes message loop

****************************************************************************/

int WINAPI MaxsiFeedback::WinMain(
    HINSTANCE hInstance,
    HINSTANCE hPrevInstance,
    LPSTR lpCmdLine,
    int nCmdShow)
{
	return BaseClass::WinMain(hInstance,hPrevInstance,lpCmdLine,nCmdShow);
}


/****************************************************************************

    FUNCTION: InitApplication(HANDLE)
    PURPOSE: Initializes window data and registers window class

****************************************************************************/

BOOL MaxsiFeedback::InitApplication(
    HANDLE hInstance)
{
    WNDCLASS  wc = {0};

    wc.lpfnWndProc = (WNDPROC) MaxsiFeedbackProc;
    wc.hInstance = (HINSTANCE)hInstance;
    wc.hIcon = LoadIconA((HINSTANCE)hInstance, "ProductIcon");
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);
    wc.lpszClassName = TEXT("MaxsiFeedback");

	if (!RegisterClass(&wc)) { return FALSE; }

	return TRUE;
}


/****************************************************************************

    FUNCTION:  InitInstance(HANDLE, int)
    PURPOSE:  Saves instance handle and creates main window

****************************************************************************/
BOOL MaxsiFeedback::InitInstance(
    HINSTANCE hInstance, 
    INT nCmdShow)
{
    LPTSTR lpszText = NULL;
    BOOL bSuccess = TRUE;

    hInst = hInstance;

    hAccTable = LoadAccelerators(hInst, TEXT("MaxsiFeedback"));

	/*if ( */ParseCommandLine();/* == false )
	{
		return FALSE;
	}*/

	// Get the screen size
	DEVMODE Dev;
	BOOL	Result	=	EnumDisplaySettings(NULL,ENUM_CURRENT_SETTINGS,&Dev);
	int w = 600;
	int h = 475;
	int x = (Result) ? (int)(Dev.dmPelsWidth - w ) / 2 : (int)CW_USEDEFAULT;
	int y = (Result) ? (int)(Dev.dmPelsHeight - h ) / 2 : (int)CW_USEDEFAULT;

	char*	WindowTitle		=	BuildString(3,"Please provide feedback about ", ProductName,"!");

    WindowHWND = CreateWindowA(
        "MaxsiFeedback",
        WindowTitle,
        (WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX ),
        x, y,
        w, h,
        NULL, NULL, hInstance, NULL );

	delete[] WindowTitle;

	if (!WindowHWND) { return FALSE; }


	ME_Window*	Parent	=	ME_WindowGetPointer(WindowHWND);

	Form = InitializeForm(new PageFeedback, Parent);

	ShowWindow(WindowHWND, nCmdShow);
    bSuccess = UpdateWindow(WindowHWND);

	return bSuccess;
}

/****************************************************************************

    FUNCTION: MainWndProc(HWND, unsigned, WORD, LONG)
    PURPOSE:  Processes messages

****************************************************************************/

LRESULT APIENTRY MaxsiFeedback::WindowProc(
    HWND hWnd, 
    UINT message, 
    WPARAM wParam, 
    LPARAM lParam)
{
	return BaseClass::WindowProc(hWnd,message,wParam,lParam);
}


DWORD MaxsiFeedback::OnThreadRegistered(HWND hWnd)
{
	PostMessage(hWnd,WM_COMMAND,0,0);

	return BaseClass::OnThreadRegistered(hWnd);
}


bool	ParseCommandLine()
{
	bool	Result		=	false;
	
	int		argc		=	0;
	char**	argv		=	0;
	char*	CommandLine	=	GetCommandLineA();

	if ( !CommandLine) { return false; }

	CommandLineToArg(CommandLine,&argc,&argv);

	if ( argc > 1 && _stricmp(argv[1],"") != 0)
	{
		char*	Command		=	argv[1];

		// Examine the input.

		size_t	ProtocolEnd		=	FindString(Command,":");

		if ( ProtocolEnd != -1 )
		{
			Command[ProtocolEnd]	=	0;

			// See what protocol was requested
			if ( _stricmp(Command,"MaxsiDistribution") != 0 )
			{
				// Uh-oh. We don't support that one!
				char*	Error	=	BuildString(3,"The Protocol '",Command,"' is not supported by MaxsiFeedback.exe");
				MessageBoxA(NULL,Error,"MaxsiInstaller",MB_ICONERROR);
				delete[]	Error;
			}
			else
			{
				Command[ProtocolEnd]	=	':';
				Command+=ProtocolEnd+strlen(":");

				// Now, isolate the name of the distribution requested.

				size_t	DistributionEnd		=	FindString(Command,"//");

				if ( DistributionEnd != -1 )
				{
					Command[DistributionEnd]	=	0;

					// Actually! We don't even care about what distribution of MD is requested.
					// Not here, at least.

					Command[DistributionEnd]	=	'/';

					Command+=DistributionEnd+strlen("//");

					// Now, check what function was requested.
					
					size_t	FunctionEnd		=	FindString(Command,"/");

					if ( FunctionEnd != -1 )
					{
						Command[FunctionEnd]	=	0;

						// See what Function was requested
						if ( _stricmp(Command,"Feedback") == 0 )
						{
							Command[FunctionEnd]	=	'/';

							Result		=	ParseDataParameters(Command+FunctionEnd+strlen(")"));
						}
						else
						{
							// Not supported!
							
							Command[FunctionEnd]	=	'/';
						}

					}

				}
			}
		}
	}
	else
	{
		Result	=	true;
	}

	DeleteCommandLineArg(argc,argv);

	if ( Result == false )
	{
		MessageBoxA(NULL,"Usage:\n\nMaxsiFeedback.exe MaxsiDistribution://Feedback/?product=[Product Name]&masterserver=[Master Server Hostname]/[Maxsi Server Resource]&username=[Username]","MaxsiFeedback",MB_ICONERROR);
	}
	
	return Result;
}

bool	ParseDataParameters(char* Parameters)
{
	size_t	ParamLen	=	strlen(Parameters);
	size_t	Read		=	0;
	bool	First		=	true;
	bool	FullValue	=	false;

	if ( ParamLen < 2 ) { return false; } // Not enough Input!

	while ( Read < ParamLen )
	{

		if ( Parameters[Read] != ((First) ? (char)'?' : (char)'&') ) { return false; } else { Read++; }

		size_t	ParameterEnd	=	FindString(Parameters+Read,"=");

		if ( ParameterEnd == -1 ) { return false; }

		char*	Parameter			=	Parameters+Read;
		Parameter[ParameterEnd]		=	0;

		char*	Value				=	Parameters+Read+ParameterEnd+1;

		size_t	ValueEnd			=	FindString(Value,"&");

		if ( ValueEnd == -1 )
		{
			FullValue	=	true;
			ValueEnd	=	strlen(Value);
		}
		else
		{
			FullValue	=	false;
		}

		Value[ValueEnd]				=	0;

		if ( _stricmp(Parameter,"Product") == 0 )
		{
			ProductName				=	BuildString(1,Value);
			DecodeURL(ProductName);
		}
		else if ( _stricmp(Parameter,"MasterServer") == 0 )
		{
			MasterServer			=	BuildString(1,Value);
			DecodeURL(MasterServer);
		}
		else if ( _stricmp(Parameter,"Username") == 0 )
		{
			SteamUserName			=	BuildString(1,Value);
			DecodeURL(SteamUserName);
		}
		else
		{
			// Unknown. Just ignore!
		}

		if ( !FullValue ) { Value[ValueEnd] = '&'; }

		First	=	false;

		Read	+=	ParameterEnd + 1 + ValueEnd;
	}

	return true;
}